<template>
  <div class="tenantMenu_main main_container user_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div class="main_main_container">

        <div class="main_main_left">
          <!--          <div class="main_main_left_top" :class="activeNum==1?'active':''">-->
          <div class="main_main_left_top">
            <el-tree
              ref="tree"
              :data="deptData"
              node-key="id"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              @node-click="treeNodeClick"
            >
              <span slot-scope="{ node, data }" class="tree-node">
                <span class="node_name">{{ data.label }}</span>
                <span class="node_operate">
                  <a class="node_operate_item" @click.stop="addNext(data)">
                    <svg-icon icon-class="树新增" />
                  </a>
                  <a class="node_operate_item" @click.stop="editDept(data)">
                    <svg-icon icon-class="树编辑" />
                  </a>
                  <a v-if="node.level>1" class="node_operate_item" @click.stop="delDept(data)">
                    <svg-icon icon-class="树删除" />
                  </a>
                </span>
              </span>
            </el-tree>
          </div>
          <div class="main_main_left_bottom">
            <!-- <a :class="activeNum==2?'active':''" @click.stop="unassignedUser">
              <div class="main_main_left_bottom_item">未分配用户</div>
            </a> -->
            <a :class="activeNum==3?'active':''" @click.stop="disabledUser">
              <div class="main_main_left_bottom_item">禁用用户</div>
            </a>
            <a v-if="codeStatus" :class="activeNum==4?'active':''" @click.stop="theApprovalIsPending">
              <div class="main_main_left_bottom_item">待审批用户</div>
            </a>
          </div>
        </div>
        <div class="main_main_right">
          <div class="main_main_right_header">
            <div class="main_main_right_header_left">
              <span>{{ currentDeptName }}</span>
              <span v-if="maxUserNumber !='-1'" class="max_user">当前账号最多可添加{{ maxUserNumber }}位用户</span>
            </div>
            <div class="main_main_right_header_right">
              <!--              <el-button v-if="currentDeptId" @click.stop="addUserToDept">添加用户</el-button>-->
              <el-button v-if="isAdmin" class="changeSuperAdmin" @click.stop="changeSuperAdmin">变更企业管理员</el-button>
            </div>
          </div>
          <div ref="table_container" class="table_container">
            <el-table
              v-if="tableColumns.length>0"
              ref="table"
              :data="tableData"
              stripe
              border
              :height="tableHeight"
              style="width: 99.9%"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              @sort-change="(column)=>{sortChange(column, this)}"
              @selection-change="(val)=>{selectionChange(val, this)}"
            >
              <el-table-column type="selection" width="70" align="center" />
              <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" />
              <el-table-column label="操作" align="center" fixed="right" width="180">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.hasApproval == '0'"
                    v-hasPermi="['system:user:edit']"
                    type="text"
                    @click.stop="audit(scope.row)"
                  >审核</el-button>
                  <el-button
                    v-if="scope.row.hasApproval !== 0"
                    v-hasPermi="['system:user:edit']"
                    type="text"
                    @click.stop="edit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    v-if="scope.row.isAdmin=='0' && scope.row.hasApproval !== 0"
                    v-hasPermi="['system:user:delete']"
                    type="text"
                    @click.stop="deleteOne(scope.row)"
                  >删除</el-button>
                  <span v-if="scope.row.isAdmin=='1'" class="el-button--text button_grey">删除</span>
                  <el-button
                    v-if="scope.row.status=='1'&&scope.row.isAdmin=='0'&& scope.row.hasApproval !== 0"
                    v-hasPermi="['system:user:disabled']"
                    type="text"
                    @click.stop="closeUser(scope.row)"
                  >禁用</el-button>
                  <span v-if="scope.row.isAdmin=='1'" class="el-button--text button_grey">禁用</span>
                  <el-button
                    v-if="scope.row.status=='0' && scope.row.hasApproval !== 0"
                    v-hasPermi="['system:user:changeStatus']"
                    type="text"
                    @click.stop="openUser(scope.row)"
                  >启用</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="main_bottom">
            <pagination
              :total="total"
              :page.sync="pageData.pageNum"
              :limit.sync="pageData.pageSize"
              :selected-num="selectionsAll.length"
              @pagination="getList"
            />
          </div>
        </div>
      </div>

    </div>

  </div>
</template>

<script>
import {
  list,
  remove,
  disabled,
  unassigned,
  updateUser,
  changeStatus,
  importMethod,
  getSecondUserNumber,
  auditList,
  audit
} from '@/api/system/user'
import { treeselect as getDeptTree, delDept as removeDept, selectUserByDeptId } from '@/api/system/dept'
import AddOrUpdate from './addOrUpdate' // 新增或编辑页面
import ChangeSuperAdmin from './changeSuperAdmin'
import AddOrUpdate_Dept from '@/views/system/dept/addOrUpdate' // 新增或编辑页面

import { mapGetters } from 'vuex'
export default {
  name: 'Index',
  computed: {
    ...mapGetters([
      'isAdmin', 'userName'
    ])
  },
  data() {
    return {
      activeNum: 1,
      deptData: [],
      currentDeptId: '',
      currentDeptName: '',
      loading: true,
      pageId: '用户管理', // 页面唯一标识
      pageExportId: '用户管理导出', // 页面导出标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      pageData2: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      codeStatus: true,
      maxUserNumber: 15,
      total: 1, // 数据一共有多少条
      mainId: 'userId', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'realName', label: '姓名', sortable: 'custom', canOrder: false },
        { prop: 'sexName', label: '性别', canOrder: false },
        { prop: 'phonenumber', label: '手机号', canOrder: false },
        { prop: 'email', label: '邮箱', canOrder: false },
        { prop: 'roleNames', label: '角色', canOrder: false },
        { prop: 'deptName', label: '部门', canOrder: false },
        // { prop: 'idCard', label: 'ID卡号', canOrder: false },
        { prop: 'isAdminName', label: '企业管理员', canOrder: false }
      ],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'realName', label: '姓名', sortable: 'custom', canOrder: false },
        { prop: 'sexName', label: '性别', canOrder: false },
        { prop: 'phonenumber', label: '手机号', canOrder: false },
        { prop: 'email', label: '邮箱', canOrder: false },
        { prop: 'roleNames', label: '角色', canOrder: false },
        { prop: 'deptName', label: '部门', canOrder: false },
        // { prop: 'idCard', label: 'ID卡号', canOrder: false },
        { prop: 'isAdminName', label: '企业管理员', canOrder: false }
      ],
      defaultExport: [],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'realName', label: '姓名', type: 'input' },
        { prop: 'phone', label: '手机号', type: 'input' },
        { prop: 'email', label: '邮箱', type: 'input' },
        // { prop: 'idCard', label: 'ID卡号', type: 'input' },
        { prop: 'isAdmin', label: '企业管理员', type: 'select', optionsName: 'isAdminOptions' }

      ],
      isAdminOptions: [
        { label: '全部', value: undefined },
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      operationData: [ // 右上角的操作按钮
        { label: '导入', perm: 'system:user:import' },
        { label: '新增', perm: 'system:user:add' },
        { label: '批量删除', perm: 'system:user:delete' },
        { label: '批量导出3', perm: 'system:user:export' },
        { label: '页面配置', perm: '' }
      ],
      allTableData: []

    }
  },
  mounted() {
    this.codeStatus = this.$store.state.user.codeStatus

    this.getDeptTree()
    // this.getLists()
    this.getSecondUserNumber()
  },
  methods: {
    getSecondUserNumber() {
      getSecondUserNumber().then(res => {
        this.maxUserNumber = res.data
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.code == 200) {
          this.$message.success('导入成功')
          this.getList()
        }
      })
    },
    deptOneClick() { // 默认点击一下第一级部门
      document.querySelector('.el-tree-node__content').click()
    },
    closeUser(row) { // 禁用
      changeStatus({ userId: row.userId, status: 0 }).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.getList()
      })
    },
    getLists() {
      list(this.pageData2).then(res => {
        this.allTableData = res.data

        this.$nextTick(() => {
          this.tableHeight = document.getElementsByClassName('main_main')[0].clientHeight -
            document.getElementsByClassName('SearchBar_main')[0].clientHeight - 120
        })
      })
    },
    openUser(row) { // 启用
      // updateUser({ userId: row.userId, status: 1 }).then(res => {
      //   this.$message({
      //     message: res.msg,
      //     type: 'success'
      //   })
      //   this.getList()
      // })
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId],
            isUse: true
          }// props
        },
        area: ['440px', '700px'],
        title: '启用用户', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    theApprovalIsPending() {
      this.activeNum = 4
      this.currentDeptId = ''
      this.currentDeptName = '待审批用户'
      this.pageData.pageNum = 1
      Object.keys(this.pageData).forEach(key => {
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn') {
          this.pageData[key] = ''
        }
      })
      this.pageData.hasApproval = '0'
      this.getList()
    },
    unassignedUser() { // 未分配用户
      this.activeNum = 2
      this.currentDeptId = ''
      this.currentDeptName = '未分配用户'
      this.pageData.pageNum = 1
      this.$refs['tree'].setCurrentKey()
      Object.keys(this.pageData).forEach(key => { // 给右边数据赋值
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn' && key !== 'isAsc') {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    disabledUser() { // 禁用用户
      this.activeNum = 3
      this.currentDeptId = ''
      this.currentDeptName = '禁用用户'
      this.pageData.pageNum = 1
      this.$refs['tree'].setCurrentKey()
      Object.keys(this.pageData).forEach(key => { // 给右边数据赋值
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn' && key !== 'isAsc') {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    getDeptTree() {
      getDeptTree().then(res => {
        this.deptData = res.data
        console.log(this.deptData)

        this.$nextTick(() => {
          this.deptOneClick()
        })
      })
    },
    getList() {
      this.tableData = []
      const cachePageData = this.$deepClone(this.pageData)
      if (this.activeNum == 1 && this.currentDeptId) {
        cachePageData.deptId = this.currentDeptId
        selectUserByDeptId(cachePageData).then(res => {
          this.tableData = res.data
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中

            this.tableHeight = document.getElementsByClassName('main_main')[0].clientHeight -
                document.getElementsByClassName('SearchBar_main')[0].clientHeight - 120
          })
        })
      }
      if (this.activeNum == 2) {
        unassigned(cachePageData).then(res => {
          this.tableData = res.data
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中
          })
        })
      }
      if (this.activeNum == 3) {
        disabled(cachePageData).then(res => {
          this.tableData = res.data
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中
          })
        })
      }
      if (this.activeNum == 4) {
        auditList(cachePageData).then(res => {
          this.tableData = res.data
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中
          })
        })
      }
    },
    addNext(data) { // 新增下级部门
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate_Dept, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            defaultValue: {
              parentId: data.id,
              parentName: data.label
            }
          }// props
        },
        area: ['440px', '300px'],
        title: '新增部门', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    editDept(data) { // 编辑部门
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate_Dept, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: data.id
          }// props
        },
        area: ['440px', '250px'],
        title: '编辑部门', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    delDept(data) { // 删除部门
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        removeDept(data.id).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getDeptTree()
        })
      }).catch(() => {})
    },
    treeNodeClick(data) { // 点击树节点
      this.activeNum = 1
      this.currentDeptName = data.label
      this.currentDeptId = data.id
      this.pageData.pageNum = 1
      Object.keys(this.pageData).forEach(key => { // 给右边数据赋值
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn' && key !== 'isAsc') {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    addUserToDept(data) {
      console.log(data)
    },
    add() {
      list().then(res => {
        if (res.data.length < this.maxUserNumber || this.maxUserNumber == -1) {
          this.$layer.iframe({// 弹框
            content: {
              content: AddOrUpdate, // 传递的组件对象
              parent: this, // 当前的vue对象
              data: {
              }// props
            },
            area: ['440px', '700px'],
            title: '新增用户', // 标题
            shadeClose: false // 点击遮罩是否关闭
          })
        } else {
          this.$message.warning('当前账号最多可添加' + this.maxUserNumber + '位用户，如需增加请联系管理员。')
          return
        }
      })
    },
    audit(row) {
      const _this = this
      this.$confirm('是否通过审核？', '审核确认', {
        distinguishCancelAndClose: true,
        cancelButtonText: '不通过', cancelButtonClass: 'cancelConfirm',
        confirmButtonText: '通过',
        type: 'warning'
      }).then(function() {
        audit({ userId: row.userId, approval: '1', companyId: row.companyId }).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch((action) => {
        if (action == 'cancel') {
          audit({ userId: row.userId, approval: '2', companyId: row.companyId }).then(res => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.getList()
          })
        }
      })
    },
    edit(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          }// props
        },
        area: ['440px', '700px'],
        title: '编辑用户', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove({ deleteIds: row[_this.mainId] }).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove({ deleteIds: deleteIds })
    },
    changeSuperAdmin() {
      this.$layer.iframe({// 弹框
        content: {
          content: ChangeSuperAdmin, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            defaultValue: {
              adminName: this.userName
            }
          }// props
        },
        area: ['440px', '250px'],
        title: '变更企业管理员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    }
  }
}
</script>
<style>
</style>
<style lang="less" scoped>
.main_main{
  height: calc(100% - 50px);
}
.main_main_container{
  width: 100%;
  height: calc(100% - 50px);
  display: flex;

  .main_main_left{
    width: 25%;
    height: calc(100% - 20px);
    margin-top: 20px;
    border-right: 1px solid rgba(51, 51, 51, 0.5);
    border-top: 2px solid rgba(51, 51, 51, 0.5);
    .main_main_left_top{
      width: 100%;
      height: calc(100% - 90px);
      overflow-y: auto;
      .el-tree{
        background-color: transparent;
      }
      /deep/ .el-tree-node__content:hover{
        background-color: rgba(56,123,252,0.5) !important;
        color: white;
      }
    }
    .main_main_left_bottom{
      width: 100%;
      .main_main_left_bottom_item{
        background-color: rgba(74, 77, 82, 0.2);
        height: 40px;
        display: flex;justify-content: flex-start;align-items: center;padding-left: 24px;
      }
      .main_main_left_bottom_item:last-child{
        border-top: 1px solid white;
      }
      .main_main_left_bottom_item:hover{
        background-color: rgba(56,123,252,.5);
        color: white;
      }
      .active{
        .main_main_left_bottom_item{
          background-color: rgba(56,123,252,1);
          color: white;
        }
      }
    }
  }
  .max_user{
    color: rgb(248, 146, 12);
    font-size: 12px;
    margin-left: 20px;
  }
  .main_main_right{
    width: 75%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .changeSuperAdmin{
    width: 120px;
  }
}
</style>
